package com.hotel.common.user.listener;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.common.config.RabbitKeyConfig;
import com.hotel.common.param.GrowthAdd;
import com.hotel.common.param.MqMsg;
import com.hotel.common.user.entity.GrowthLog;
import com.hotel.common.user.entity.Level;
import com.hotel.common.user.mapper.GrowthLogMapper;
import com.hotel.common.user.mapper.LevelMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class GrowthRabbitListener {

    @Autowired
    private GrowthLogMapper growthLogMapper;


    @Autowired
    private LevelMapper levelMapper;

    @RabbitListener(queues = RabbitKeyConfig.Q_USER_GROWTH)
    public void growthListener(MqMsg msg){

        System.out.println("msg = " + msg);

        if (msg.getType() == 5){ // 积分成长值

            // 得到需要增加的积分
            GrowthAdd growthAdd =(GrowthAdd) msg.getMsg();

            // 1.根据uid 查询该用户积分  没有则直接插入积分  有增加积分

            QueryWrapper<Level> levelQueryWrapper = new QueryWrapper<>();
            levelQueryWrapper.eq("user_id",growthAdd.getUid());

            List<Level> levelList = levelMapper.selectList(levelQueryWrapper);

            Level level = null;
            if (levelList == null || levelList.size() == 0){// 没有积分直接插入

                level  = new Level();

                level.setLevel(1);
                level.setGrowths(growthAdd.getGrowth());
                level.setName("练气");
                level.setUserId(growthAdd.getUid());
                level.setCtime(new Date());

                levelMapper.insert(level);
            }else { // 积分存在

                level = levelList.get(0);

                // 增加积分
                level.setGrowths(level.getGrowths() + growthAdd.getGrowth());

                // 等级改变
                if (level.getGrowths()<100){
                    level.setLevel(1);
                    level.setName("练气");
                }else if (level.getGrowths()<1000){
                    level.setLevel(2);
                    level.setName("筑基");
                }else if (level.getGrowths()<10000) {
                    level.setLevel(2);
                    level.setName("金丹");
                }
                levelMapper.updateById(level);
            }

            // 记录日志
            GrowthLog growthLog = new GrowthLog();
            growthLog.setCtime(new Date())
                    .setUserId(growthAdd.getUid())
                    .setType(growthAdd.getType())
                    .setInfo(growthAdd.getType()+"积分增加"+growthAdd.getGrowth());
            growthLogMapper.insert(growthLog);

        }

    }

}
